clear; 
clc;
% 
Subjects;
[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;
EEG = pop_loadset(subject.CW.EpochData.SphereUnambiguousResponse.dataFilename);
load('CW_Chanlocs.mat');
elecSelection = {'P10'}; %'P10'

data = [];
for i = 1:length(elecSelection)
    esIdx(i) = find(strcmp(elecSelection{i},{CW_Chanlocs.labels}));
    idata(:,:,i) = squeeze(EEG.data(esIdx(i),:,:))';
    data = [data; idata(:,:,i)];
end;

% rd = rand(length(data(:,1)),1);
% [rd,rdIdx] = sort(rd);
% data = [data,data(rdIdx,:)];

% selectedChanlocs = CW_Chanlocs(esIdx);
% 
data = [data(1:10,:)];
for i = 1:length(data(:,1));
    smoothdata(i,:) = GaussianSmooth(data(i,:)', 30);
end

[weights,sphere,compvars,bias,signs,lrates,activations] = runica(data,'extended', 5, 'maxsteps',5000);

% t = tfc.times - 5000;

times = [EEG.times]; %,EEG.times+10000

%% Plot components
figure;
for i = 1:length(data(:,1));
    h = subplot(5,2,i);
     plot (times, activations(i,:))
    xlim([-4000 4000]);
      title (['Component ' num2str(i)]);
      set(h, 'xgrid', 'on');
%     ylim([-10 10]);
%     P = get(h, 'Position');
%     newH = axes('Position', [P(1)+(P(3)*.7) P(2)+P(4)/2 P(3)*.3 P(4)/2]);
%     
% Plot heads in componentplots
%     values = weights(:,i);
%     
%     topoplot(values, selectedChanlocs, ...
%         'style','both', ... % just "style: map" doesn't seem to work..
%         'numcontour', 0, ...
%         'electrodes', 'on');
%     set(newH,'clim',[-2 2])
    
%     set(h, 'xtick', [-2000 0 2000]);
%     set(h, 'xticklabel', {'-2s', '-M-', '2s'});

end

% figure;
% for i = 1:length(smoothdata(:,1));
%     h = subplot(5,2,i);
%      plot (times, smoothdata(i,:))
%     xlim([-4000 4000]);
%       title (['Trial ' num2str(i)]);
%       set(h, 'xgrid', 'on');
% end

% Plot weights
figure;
imagesc(weights, [-1,1])
colorbar; 
% if length(elecSelection) == 1
%     title (['Subject CW - SphereUnambiguousResponse - Electrode P10 - ICA over trials']);
% else title (['Subject CW - SphereUnambiguousResponse - Electrodes P10 and OcO4 - ICA over trials']);
% end
xlabel ('trials'); ylabel ('components');


% % Plot heads
% % for i = 1:15
% %         values = weights(:,i);
% %     figure;
% %     topoplot(values, selectedChanlocs, ...
% %         'style','both', ... % just "style: map" doesn't seem to work..
% %         'numcontour', 6, ...
% %         'electrodes', 'labels');
% %     title (['Component ' num2str(i)])
% % end;
% 
return;